package cn.example.practice.filter;

import cn.example.practice.model.User;
import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;

@WebFilter(filterName = "AuthenticationFilter", urlPatterns = "/*")
public class AuthenticationFilter implements Filter {
    // 不需要登录就能访问的路径
    private static final List<String> PUBLIC_PATHS = Arrays.asList(
            "/toLoginServlet",
            "/loginServlet",
            "/admin/toProductManagerServlet",
            "/admin/productManagerServlet",
            "/productImageServlet",
            "/toRegisterServlet",
            "/userRegisterServlet",
            "/css/",
            "/js/",
            "/img/",
            "/image/noproduct.png",
            "/verifyCodeImgServlet"
    );

    @Override
    public void init(FilterConfig filterConfig) {
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        HttpServletResponse httpResponse = (HttpServletResponse) response;

        String requestPath = httpRequest.getServletPath();

        // 检查是否是公开访问路径
        boolean isPublicPath = PUBLIC_PATHS.stream()
                .anyMatch(requestPath::startsWith);

        if (isPublicPath) {
            chain.doFilter(request, response);
            return;
        }

        // 检查用户是否已登录
        HttpSession session = httpRequest.getSession(false);
        User loginUser = session != null ? (User) session.getAttribute("loginUser") : null;

        if (loginUser == null) {
            httpResponse.sendRedirect(httpRequest.getContextPath() + "/toLoginServlet");
            return;
        }

        chain.doFilter(request, response);
    }

    @Override
    public void destroy() {
    }
}
